package edu.uc.labs.MobilePrinting;

import java.io.File;

import javax.xml.xpath.XPathFactoryConfigurationException;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;



public class Configuration {

	final private String CONFIGFILE = "defaults.xml";
	//final private String INSTALLDIR = getInstallDir();
	final private String OS 		= System.getProperty("os.name");
	final private String HOMEDIR 	= System.getProperty("user.home");
	
	// CONSTANT DIRECTORIES
	final private String PREFS = "preferences";
	final private String LOGS  = "logs";
	
	final private int SLEEP = 10000;
	
	Logger logger;
	
	public Configuration() {
		logger = getConfigLog();
		logger.debug("Logger for Configuration...");
	}
	
	public XMLConfiguration getConfiguration() {
		try {
			String file = getInstallDir() + PREFS + getDelim() + CONFIGFILE;
			XMLConfiguration config = new XMLConfiguration( file );	
			return config;
		} catch ( ConfigurationException cex ){
			logger.error(cex.toString());
		}
	}

	public String getInstallDir() {
		String dir = null;
		if(OS.startsWith("Win")){
			dir = HOMEDIR + "\\Application Data\\ucit\\MobilePrinting\\";
		} else if (OS.startsWith("Mac")){
			dir = HOMEDIR + "/Library/Application Support/UCit/MobilePrinting/";
		} else {
			dir = HOMEDIR + "/.ucit/MobilePrinting/";
		}
		return dir;
	}

	public String getDelim(){
		String delim = null;
		if(OS.startsWith("Win")){
			delim = "\\";
		}else{
			delim = "/";
		}
		return delim;
	}
	
	public int getSleep() {
		return SLEEP;
	}
	
	private Logger getConfigLog() {
		Logger log = Logger.getLogger("MobilePrintingConfiguration");
		String fileName = getInstallDir() + LOGS + getDelim() + "Configuration.log";
		Level logLevel = Level.DEBUG;
		try {

			PatternLayout layout = new PatternLayout("%d - %c - %p - %m%n");
			RollingFileAppender R = new RollingFileAppender(layout, fileName, false);
			R.setMaxFileSize("500KB");
			R.setMaxBackupIndex(1);

			ConsoleAppender c = new ConsoleAppender(layout);
			log.addAppender(R);
			log.addAppender(c);
			log.setLevel(logLevel);
		} catch (Exception e) {
			System.err.println(e.toString());
		}
		return log;

	}
}
